<template>
  <tl-sub-page render="div" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <a id="basic" class="step-position">&nbsp;</a>
      <div class="tl-form-line-title">
        立项信息
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目经理" prop="projectmanager">
            <el-input v-model="model.projectmanager" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目名称" prop="projectname" :rules="rules.rulesForInfo">
            <el-input v-model="model.projectname"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目级别" prop="projectlevel" :rules="rules.rulesForInfo">
            <el-row type="flex">
              <el-select v-model="model.projectlevel" disabled>
                <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
              <el-button type="primary" icon="el-icon-edit-outline" class="levelButton" @click="openChangeLevelDialog" :disabled="!model.projectlevel"></el-button>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectnumber">
            <el-input v-model="model.projectnumber" disabled placeholder="系统自动生成"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.rulesForInfo">
            <el-date-picker v-model="model.planstartdate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planStart"> </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划结束日期" prop="planenddate" :rules="rules.rulesForInfo">
            <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planEnd"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目周期" prop="bidcycle">
            <el-input v-model="model.bidcycle" class="unitInput" disabled placeholder="系统自动计算"><template #append>天</template></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Sponsor" prop="sponsorcode" :rules="rules.rulesForInfo">
            <tl-ref-user v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Owner" prop="ownercode" :rules="rules.rulesForInfo">
            <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" dataType="code" :singleSelect="true" :disabled="disableEditSubmit || disableSave"> </tl-ref-user>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="historyLevel && model.projectlevel !== historyLevel">
        <el-col :span="12">
          <el-form-item label="原项目级别">
            <el-input v-model="historyLevel" class="tl-ref-selector" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="model.projectlevel && tempprojectlevel && model.projectlevel !== tempprojectlevel">
        <el-col :span="24">
          <el-form-item label="项目级别调整原因" prop="changelevelreason" :rules="rules.rulesForInfo">
            <el-input v-model="model.changelevelreason" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <a id="background" class="step-position">&nbsp;</a>
      <div class="tl-form-line-title">
        项目背景
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目背景概述" prop="background" :rules="rules.rulesForInfo">
            <el-input v-model="model.background" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目目标" prop="target" :rules="rules.rulesForInfo">
            <el-input v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <a id="apply" class="step-position">&nbsp;</a>
      <div class="tl-form-line-title">
        申请信息
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
            <el-input v-model="model.username" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人工号" prop="usercode">
            <el-input v-model="model.usercode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人部门" prop="applydeptname">
            <el-input v-model="model.applydeptname" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人公司" prop="applyorgname">
            <el-input v-model="model.applyorgname" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="GpmWfForm" :sourceId="model.approvalhistoryid" />
    <tl-sd-Project-resource-pool-ref ref="sdProjectResourcePoolRef" :title="'决策组选择'" @confirm="getMpmProjectResourceData" :fieldKey="'usercode'" :fieldValue="'username'" :externalSelectedRowKeys="approvalExtraParam === 'LINInvite' ? model.invitedecisionusercode : model.decisionusercode" :isSingleSelect="false" :externalQueryParam="externalDQueryParamForPool" :initDisplayData.sync="LINInviteParam"> </tl-sd-project-resource-pool-ref>
    <tl-change-level-ref ref="changeLevelRef" @confirm="confirmChangeLevel"></tl-change-level-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
import { mixin_approval_edit_edit } from '../../../../mixins/mixin_approval_edit'
import { mixin_page_fields_custom } from '@/views/gpm/gpmProjectInfo/mixin/mixin_page_fields_custom.js'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
// import tlmpmProjectResourcePoolRef from '@/views/mpm/mpmProjectResourcePool/refList'
import tlSdProjectResourcePoolRef from '../../gpmProjectResourcePool/refList.vue'
// import tlchangeRef from '@/views/mpm/mpmProject/refListChange'
import tlChangeLevelRef from './changeLevelCompent'
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_list, mixin_approval_edit_edit],
  // components: { tlmpmProjectResourcePoolRef, tlchangeRef, tlChangeLevelRef },
  components: { tlChangeLevelRef, tlSdProjectResourcePoolRef },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error('请输入内容'))
      } else {
        return callback()
      }
    }
    return {
      bidrequired: true,
      moduleTitle: '项目立项',
      urlPrefix: '/sd/project/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/mpm/project/queryOrgByDeptId',
        list: '/cbo/approvalNodeIns/list',
        changeList: '/mpm/project/changeList',
        add: '/sd/project/doSave',
        edit: '/sd/project/doSave',
        queryCeoInfo: '/sd/project/queryCeo',
        projectApproval: '/sd/project/projectApproval',
        approvalList: '/sd/project/approvalList',
        // 更新项目部分字段
        updateProjectPartFields: '/sd/project/updateProjectPartFields',
        // 传阅反馈
        checkCirculatedRecord: '/sd/project/checkCirculatedRecord'
      },
      tabName: 'projectbasicinfo',
      sorterInfo: {
        // 排序参数
        sidx: 'id',
        sord: 'desc'
      },
      midChangePoint: true,
      datas: [],
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      rowKeyStr: 'CODE',
      loading: false,
      visible: false,
      listMode: true,
      externalMQueryParamForPool: {},
      externalDQueryParamForPool: {},
      // 项目立项规则校验重写
      addRules: {
        // 基本信息TAB表单校验
        rulesForInfo: [{ validator: validateForTab, tabname: 'projectbasicinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        // 案例概述TAB表单验证
        rulesForCustomeryInfo: [{ validator: validateForTab, tabname: 'projectcustomerinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }],
        rulesForCompetitorInfo: [{ validator: validateForTab, tabname: 'projectcompetitorinfo', trigger: 'change' }, { required: 'true', message: '请输入内容', trigger: 'change' }]
      },
      // 项目级别默认编码值，根据选择的机会点确定
      tempprojectlevel: '',
      // 项目级别默认显示值，根据选择的机会点确定
      tempdispprojectlevel: '',
      // CEO信息
      tempdecisionusercode: '',
      tempdecisionusername: '',
      mainHeight: 1000,
      // 审批节点配置的额外参数
      extraParam: '',
      // 判断是否是审批组件调用
      fromApproval: '',
      oldprojectlevel: '',
      // 项目等级，例：网级、省级等
      maxLevel: -1,
      // 微前端调用该组件时传递的来源类型
      sourceType: '',
      // 微前端调用时传递的机会点编号
      chancecode: '',
      contractchanged: false
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    },
    isApprovalCEO: {
      type: String,
      default: ''
    },
    approvalExtraParam: {
      type: String,
      default: ''
    }
  },
  computed: {
    historyLevel() {
      if (this.model.levelhistory) {
        return JSON.parse(this.model.levelhistory.replace(/\//g, '')).oldprojectlevel
      } else {
        return ''
      }
    },
    LINInviteParam() {
      if (this.approvalExtraParam === 'LINInvite') {
        return this.model.invitedecisionusername
      } else {
        return this.model.decisionusername
      }
    }
  },
  methods: {
    beforeOpenAddDialog(editForm, rowData) {
      this.$refs[editForm].projectModel = rowData
      return true
    },
     /** 打开新增对话框实现 */
    openAddDialog(editForm, rowData) {
      if (!this.beforeOpenAddDialog(editForm, rowData)) {
        return
      }
      this.$refs[editForm].projectmodel = rowData
      this.$refs[editForm].isAdd = true
      this.$refs[editForm].visible = true
      this.$refs[editForm].disableEditSubmit = false
      this.$nextTick(() => {
        this.afterOpenAddDialog(editForm, rowData)
      })
    },
    localClose() {
    },
    changeLevel() {
      if (this.model.sdrange) {
        switch (this.model.sdrange) {
          // 网级交付
          case '1': {
            this.$set(this.model, 'projectlevel', '0')
            this.$set(this.model, 'projectdefaultlevel', '0')
            break
          }
          // 地电、省级交付
          case '2':
          case '3': {
            if (this.model.ourprocductfund) {
              let fund = parseFloat(this.model.ourprocductfund)
              if (fund >= 500) {
                this.$set(this.model, 'projectlevel', '0')
                this.$set(this.model, 'projectdefaultlevel', '0')
                break
              } else if (fund >= 100) {
                this.$set(this.model, 'projectlevel', '1')
                this.$set(this.model, 'projectdefaultlevel', '1')
                break
              } else {
                this.$set(this.model, 'projectlevel', '2')
                this.$set(this.model, 'projectdefaultlevel', '2')
                break
              }
            } else {
              this.$set(this.model, 'projectlevel', '2')
              this.$set(this.model, 'projectdefaultlevel', '2')
              break
            }
          }
          // 市县级/非电交付
          case '4':
          case '5': {
            if (this.model.ourprocductfund) {
              let fund = parseFloat(this.model.ourprocductfund)
              if (fund >= 500) {
                this.$set(this.model, 'projectlevel', '1')
                this.$set(this.model, 'projectdefaultlevel', '1')
                break
              } else if (fund >= 100) {
                this.$set(this.model, 'projectlevel', '2')
                this.$set(this.model, 'projectdefaultlevel', '2')
                break
              } else {
                this.$set(this.model, 'projectlevel', '3')
                this.$set(this.model, 'projectdefaultlevel', '3')
                break
              }
            } else {
              this.$set(this.model, 'projectlevel', '3')
              this.$set(this.model, 'projectdefaultlevel', '3')
              break
            }
          }
        }
      }
    },
    // 更新机会点编号
    changeChanceClue(val) {
      this.$set(this.model, 'chanceclue', val)
    },
    // 更新可参与金额
    changeOurProductFund(val) {
      this.$set(this.model, 'ourprocductfund', val)
      this.changeLevel()
    },
    changeContract() {
      this.contractchanged = true
    },
    doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      if (this.isAdd) {
        this.doAdd()
      } else {
        this.doEdit()
      }
    },
    beforeSubmit() {
      let copymodel = {}
      Object.assign(copymodel, this.model)
      this.$set(this.model, 'basicInfo', copymodel)
      return true
    },
    planStart(e) {
      if (this.model.planenddate) {
        var a = new Date(this.model.planstartdate).getTime()
        var b = new Date(this.model.planenddate).getTime()
        if (a > b) {
          this.$tap.alert('开始日期不得大于结束日期。', 'warning')
          this.$set(this.model, 'planstartdate', '')
          this.$set(this.model, 'bidcycle', '')
          return
        } else {
          var t = b - a
          var days = Math.ceil(t / (1000 * 3600 * 24)) + 1
          this.$set(this.model, 'bidcycle', days)
        }
      }
    },
    planEnd(e) {
      if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined') {
        this.$tap.alert('请先选择计划开始日期！', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var c = new Date(this.model.planenddate).getTime()
      var d = new Date(this.model.planstartdate).getTime()
      if (c < d) {
        this.$tap.alert('开始日期不得大于结束日期。', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var a = c - d
      var days = Math.ceil(a / (1000 * 3600 * 24)) + 1
      this.$set(this.model, 'bidcycle', days)
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.projectmodel.projectid = this.projectmodel.id
        delete this.projectmodel.id
        this.model = JSON.parse(JSON.stringify(this.projectmodel))
      }
    },
    projectSubmit() {
      let that = this
      const basicInfoValidate = new Promise(function (resolve, reject) {
        that.$refs.form.validate((valid, res) => {
          if (valid) {
            resolve()
          } else {
            reject("按要求填写表单数据项，包括必填项，数据格式等")
          }
        })
      })
      that.submitLoading = true
      Promise.all([basicInfoValidate]).then(async () => {
        let saveresult = await that.addBase()
        if (saveresult) {
          this.saveLoading = true
          const parameter = { id: that.model.id }
          putAction(this.url.projectApproval, parameter)
            .then((res) => {
              if (res.success) {
                this.queryData(that.model.id).then((_) => {
                  this.loaded()
                  this.saveLoading = false
                  this.submitLoading = false
                })
                this.$tap.alert('提交审批成功', 'success')
                // 审批历史加载信息
                this.doQuery()
              } else {
                this.$tap.alert(res.message, 'warning')
                this.saveLoading = false
                this.submitLoading = false
              }
            })
            .catch((err) => {
              this.saveLoading = false
              this.submitLoading = false
            })
        }
      }).catch((error) => {
        this.$tap.alert(error)
        that.submitLoading = false
      })
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.$emit('refresh')
            this.$emit('loaded', this.model)
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 选择项目所属部门
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.contractchanged = false
      this.resizeHandler()
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          this.queryCeoInfo(this.user.code)
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.$refs.form.clearValidate()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            // 获取项目等级
            this.$refs.form.clearValidate()
            // this.getMaxLevel()
            this.queryCeoInfo(this.model.projectmanagercode)
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            // 获取项目等级
            this.$refs.form.clearValidate()
            this.queryCeoInfo(this.model.projectmanagercode)
            // this.getMaxLevel()
            this.loaded()
          })
        }
      })
      this.datas = []
      this.loadData({ currentPage: 1 })
    },
    // 查询决策组成员信息
    queryCeoInfo(managercode) {
      let params = {
        managercode: managercode
      }
      let that = this
      getAction(that.url.queryCeoInfo, params).then((res) => {
        if (res.success) {
          let code = []
          let name = []
          res.result.forEach((element) => {
            code.push(element.code)
            name.push(element.name)
          })
          let codes = ',' + code.join(',') + ','
          let names = name.join(',')
          if (that.isAdd) {
            this.$set(this.model, 'decisionusercode', codes)
            this.$set(this.model, 'decisionusername', names)
          }
          // 将CEO信息存到中间变量中
          that.tempdecisionusercode = codes
          that.tempdecisionusername = names
        }
      })
    },
    // 加载审批历史信息
    queryApprovalHistory(params) {
      this.loading = true
      getAction(this.url.approvalList, params)
        .then((res) => {
          if (res.success) {
            if (res.result.dataList === null) {
              this.datas = []
              this.pageInfo.totalCount = 0
            } else {
              this.datas = res.result.dataList
              this.pageInfo.totalCount = res.result.totalCount
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 加载审批历史列表数据 */
    loadData(paramMap) {
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      this.sorterInfo.sidx = 'approvaldate'
      var params = this.getQueryParams()
      // 数据查询
      this.queryApprovalHistory(params)
    },
    /** 执行查询 */
    doQuery() {
      this.loadData({ currentPage: 1 })
    },
    /** 获取查询参数 */
    getQueryParams() {
      let param = {
        qry_sourcetype: 'GpmWfForm',
        qry_sourceid: 0
      }
      if (!this.isAdd) {
        param.qry_wfsourceid = this.id
      }
      Object.assign(param, this.sorterInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      return param
    },
    /** 表格列排序 */
    doSortChange(columnInfo, prop, order) {
      if (columnInfo.column === null) {
        return
      }
      // 不排序
      if (validateNull(columnInfo.order)) {
        this.loadData({})
        return
      }
      // 升序或者降序排序
      if (columnInfo.column.sortBy) {
        this.sorterInfo.sidx = columnInfo.column.sortBy
      } else {
        this.sorterInfo.sidx = columnInfo.prop
      }
      this.sorterInfo.sord = columnInfo.order.replace('ending', '')
      this.loadData({})
    },
    /** 每页大小改变 */
    doChangeSize(val) {
      if (this.pageInfo.pageSize !== val) {
        this.pageInfo.pageSize = val
        this.pageInfo.currentPage = 1
        this.loadData({})
      }
    },
    /** 页面跳转 */
    doChangeIndex(val) {
      if (this.pageInfo.currentPage !== val) {
        this.pageInfo.currentPage = val
        this.loadData({})
      }
    },
    drawDiagram(map) {
      /* eslint-disable*/
      $('#history-myflow').html('')
      let restore = map.strdiagram
      restore = restore.replace(/'/g, '"')
      if (restore !== '') {
        restore = JSON.parse(restore)
      }
      let history = map.strhistory
      history = history.replace(/'/g, '"')
      history = history.replace(/activeRects/g, '"activeRects"')
      history = history.replace(/historyRects/g, '"historyRects"')
      history = history.replace(/rects/g, '"rects"')
      history = history.replace(/paths/g, '"paths"')
      history = history.replace(/code/g, '"code"')
      if (history !== '') {
        history = JSON.parse(history)
      }
      $('#history-myflow').myflow(
        $.extend(false, {
          basePath: '',
          restore: restore,
          editable: false,
          ...history
        })
      )
    },
    // 项目级别变更后，清空项目经理和决策组--2-7todo 暂时取消
    clear() {
      if (this.model.projectmanagercode || this.model.decisionusercode) {
        this.$set(this.model, 'projectmanagercode', '')
        this.$set(this.model, 'projectmanager', '')
        this.$set(this.model, 'decisionusercode', '')
        this.$set(this.model, 'decisionusername', '')
      }
    },
    /** 打开决策组成员参照 */
    openMpmProjectResourcePoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert('请先选择项目级别！', 'warning')
        this.$refs.sdProjectResourcePoolRef.visible = false
      } else {
        this.externalDQueryParamForPool = {
          projectlevel: projectlevel,
          projecttype: projecttype
        }
        this.$refs.sdProjectResourcePoolRef.visible = true
      }
    },
    /** 获取决策组成员参照数据 */
    getMpmProjectResourceData(selectionRow, selectKey, selectionValue) {
      // 如果是林总邀请审批
      if (this.approvalExtraParam === 'LINInvite') {
        let resultcodes = ''
        let resultnames = ''
        if (Array.isArray(selectionRow)) {
          if (selectionRow.length > 0) {
            let code = []
            let name = []
            selectionRow.forEach((element) => {
              code.push(element.usercode)
              name.push(element.username)
            })
            if (code.length > 0 && name.length > 0) {
              resultcodes += ',' + code.join(',') + ','
              resultnames += name.join(',')
            }
          }
        } else {
          if (selectionRow.usercode) {
            resultcodes += ',' + selectionRow.usercode + ','
            resultnames += selectionRow.username
          }
        }
        this.$set(this.model, 'invitedecisionusercode', resultcodes)
        this.$set(this.model, 'invitedecisionusername', resultnames)
      } else {
        // 如果是AB项目
        if (this.model.projectlevel === '0' || this.model.projectlevel === '1') {
          // 将CEO数据分割为数组
          let tempdecisionusercodeArr = this.tempdecisionusercode.split(',')
          let resultcodes = this.tempdecisionusercode
          let resultnames = this.tempdecisionusername
          if (Array.isArray(selectionRow)) {
            if (selectionRow.length > 0) {
              let code = []
              let name = []
              selectionRow.forEach((element) => {
                // 移除选择的人员中的CEO数据
                if (tempdecisionusercodeArr.indexOf(element.usercode) < 0) {
                  code.push(element.usercode)
                  name.push(element.username)
                }
              })
              if (code.length > 0 && name.length > 0) {
                resultcodes += code.join(',') + ','
                resultnames += ',' + name.join(',')
              }
            }
          } else {
            if (selectionRow.usercode && tempdecisionusercodeArr.indexOf(selectionRow.usercode) < 0) {
              resultcodes += selectionRow.usercode + ','
              resultnames += ',' + selectionRow.username
            }
          }
          this.$set(this.model, 'decisionusercode', resultcodes)
          this.$set(this.model, 'decisionusername', resultnames)
        } else {
          // 如果是CD级项目
          let resultcodes = ''
          let resultnames = ''
          if (Array.isArray(selectionRow)) {
            if (selectionRow.length > 0) {
              let code = []
              let name = []
              selectionRow.forEach((element) => {
                code.push(element.usercode)
                name.push(element.username)
              })
              let codes = code.join(',')
              resultcodes = codes ? ',' + codes + ',' : ''
              resultnames = name.join(',')
            }
          } else {
            resultcodes = ',' + selectionRow.usercode + ','
            resultnames = selectionRow.username
          }
          this.$set(this.model, 'decisionusercode', resultcodes)
          this.$set(this.model, 'decisionusername', resultnames)
        }
      }
    },
    /** 打开机会点参照 */
    openChanceclueDialog() {
      if (!this.model.sourcetype) {
        this.$tap.alert('请先选择项目来源！', 'warning')
      } else {
        this.$refs.contractRef.visible = true
      }
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id).then((_) => {
              this.loaded()
            })
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          // this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    //数据库字符串对象去特殊字符
    loaded() {
      this.$emit('loaded', this.model)
      // 通过项目级别编码为项目级别显示值赋值
      if (this.model.projectlevel && !this.model.projectdefaultlevel && this.codeModel) {
        let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
        // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
        this.tempprojectlevel = this.model.projectlevel
        this.tempdispprojectlevel = tempLevelData.name
      }
      // 通过项目默认等级为tempprojectlevel和tempdispprojectlevel赋值
      if ((this.model.projectdefaultlevel || this.model.projectdefaultlevel === '0') && this.codeModel) {
        let tempDefaulLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectdefaultlevel)
        this.tempprojectlevel = this.model.projectdefaultlevel
        this.tempdispprojectlevel = tempDefaulLevelData.name
      }
      // 林总审批用
      this.oldprojectlevel = this.model.projectlevel
      // 给midChangePoint赋初始值
      if (this.model.chanceclue) {
        this.midChangePoint = this.model.chanceclue.split(',') <= 1
      }

      // 若为不可编辑状态则清空placeholder
      if (this.disableEditSubmit || this.disableSave) {
        this.$refs.form.fields.forEach(item => {
          if (item.$children[1].$options._componentTag === "el-input") {
            item.$children[1].getInput().placeholder = ''
          }
        })
      }
      this.$refs.form.clearValidate()
    },
    close() {
      this.tempprojectlevel = ''
      this.tempdispprojectlevel = ''
      this.maxLevel = -1
    },
    /** 打开调整项目级别的弹框 **/
    openChangeLevelDialog() {
      this.$refs.changeLevelRef.projectlevelList = this.codeModel.projectlevelList
      this.$refs.changeLevelRef.dispprojectdefaultlevel = this.tempdispprojectlevel
      this.$set(this.$refs.changeLevelRef.model, 'projectlevel', this.model.projectlevel)
      this.$set(this.$refs.changeLevelRef.model, 'dispprojectlevel', this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel).name)
      this.$set(this.$refs.changeLevelRef.model, 'changelevelreason', this.model.changelevelreason)
      this.$refs.changeLevelRef.visible = true
    },
    /** 填写调整项目等级原因后回写数据 **/
    confirmChangeLevel(data) {
      this.$set(this.model, 'projectlevel', data.projectlevel)
      this.$set(this.model, 'changelevelreason', data.changelevelreason)
    },
    afterSubmit() {
      this.loaded()
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd')
    },
    openMeetDialog(val, editForm) {
      if (val === '1') {
        window.open('https://meet.topscomm.com/meet/meetManage')
      }
    },
    // 审批专用函数
    beforeApproval(resolve, reject) {
      // PMO标准化审批
      if (this.uiOperateState === 3) {
        let that = this
        const basicInfoValidate = new Promise(function (resolve, reject) {
          that.$refs.form.validate((valid, res) => {
            if (valid) {
              resolve()
            } else {
              reject("按要求填写表单数据项，包括必填项，数据格式等")
            }
          })
        })
        that.submitLoading = true
        Promise.all([basicInfoValidate]).then(async () => {
          let saveresult = await that.addBase()
          if (saveresult) {
            that.submitLoading = false
            resolve('保存成功')
          } else {
            that.submitLoading = false
            reject('保存失败')
          }
        }).catch((error) => {
          this.$tap.alert(error)
          that.submitLoading = false
          reject('保存失败')
        })
      }
    },
    autoSelect() {
      this.$nextTick(() => {
        if (this.autoSelected === 0 && this.isAdd) {
          if (this.sourceType === 'chance') {
            // 模拟手动选择机会点
            this.$set(this.model, 'projectsource', '2')
            this.changeSource()
            setTimeout(() => {
              let param = {
                qry_chancecode: this.chancecode,
                projectsource: this.model.projectsource,
                usercode: this.user.code,
                currentPage: 1,
                pageSize: 10
              }
              getAction('/mpm/project/changeList', param).then((res) => {
                if (res.success) {
                  this.getChanceclueData(res.result.dataList)
                } else {
                  this.$tap.alert('获取线索/机会点列表错误，请联系管理员')
                }
              })
            }, 1000)
          }
        }
        this.autoSelected = 1
      })
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    // 抽屉组件必有
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>
<style scoped>
.formLine {
  position: relative;
  margin: 0 auto;
  width: 900px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.formLineTitle {
  position: absolute;
  left: 12%;
  font-family: "kaiTi";
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
</style>
